﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.DatabaseAccessor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Abc.Core;
public class SqlSugarAopFilter : ISqlSugarAopFilter
{
    /// <summary>
    /// 全局过滤器
    /// </summary>
    /// <param name="dbProvider"></param>
    public void Filter(ISqlSugarClient dbProvider)
    {
        try
        {
            List<Type> types = App.EffectiveTypes.Where(a => !a.IsAbstract && a.IsClass
         && (a.GetCustomAttributes(typeof(SugarTable), true)?.FirstOrDefault() != null
         || a.GetCustomAttributes(typeof(TableAttribute), true)?.FirstOrDefault() != null)
         && (a.GetCustomAttributes(typeof(TenantTestAttribute), true)?.FirstOrDefault() != null)
         ).ToList();

            foreach (var entityType in types)
            {
                // 共享数据表，共享 Schema (基于 TenantId 的方式)
                if (entityType != null && !entityType.GetProperty("TenantId").IsEmpty())
                {
                    var tenantId = AppEx.TenantId;
                    //判断实体类中包含TenantId属性
                    //构建动态Lambda
                    var lambda = DynamicExpressionParser.ParseLambda
                    (new[] { Expression.Parameter(entityType, "it") },
                     typeof(bool), $"{nameof(ITenantEntity.TenantId)} ==  @0",
                      tenantId);
                    dbProvider.QueryFilter.Add(new TableFilterItem<object>(entityType, lambda)); //将Lambda传入过滤器
                }

            }
        }
        catch (Exception ex)
        {


        }
    }
}
